package com.lzp.java.concurrent.lock.reentrantlock;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 测试公平锁和非公平锁
 *
 * @author lzp
 * @date 2020/04/12
 */
public class FairUnfairLock {
    public static void main(String[] args) throws InterruptedException {
        Thread[] threads = new Thread[10];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new PrintTask());
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
            TimeUnit.MILLISECONDS.sleep(100);
        }

    }
}

/**
 * 非公平锁：线程0打印完第一份，其他九个线程还未唤醒，线程0可以继续获取锁。
 */
class PrintTask implements Runnable {
    private Lock lock = new ReentrantLock(false);

    @Override
    public void run() {
        print();
    }

    public void print() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "第一次打印...");
            int duration = new Random().nextInt(10) + 1;
            TimeUnit.MILLISECONDS.sleep(duration * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        // 再次获取锁打印
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "第二次打印...");
            int duration = new Random().nextInt(10) + 1;
            TimeUnit.MILLISECONDS.sleep(duration * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}


